//
// Created by antler on 2018/12/15.
//

#include "ScreenUtils.h"

#include "LuaJavaHelper.h"

static jmethodID methodID_Size_GetWidth = nullptr;
static jmethodID methodID_Size_GetHeight = nullptr;

namespace ScreenUtils {

    Size getSize() {
        Size size = Size::INVALID;

        do {
            JNIEnv *env = LuaJavaHelper::getInstance()->getEnv();
            if (!env) {
                break;
            }

            jobject jrect = LuaJavaHelper::callStaticObjectMethod(env, CLASS_NAME_SCREENUTILS,
                                                                  METHOD_NAME_SCREENUTILS_GETSIZE,
                                                                  METHOD_SIG_SCREENUTILS_GETSIZE);
            ScopedLocalRef<jobject> localObjectRect(env, jrect);
            if (!localObjectRect) {
                break;
            }

            ScopedLocalRef<jclass> localClassRect(env, env->GetObjectClass(localObjectRect));
            if (!localClassRect) {
                break;
            }

            if (methodID_Size_GetWidth == nullptr) {
                methodID_Size_GetWidth = env->GetMethodID(localClassRect, "getWidth", "()I");
            }

            if (methodID_Size_GetHeight == nullptr) {
                methodID_Size_GetHeight = env->GetMethodID(localClassRect, "getHeight", "()I");
            }

            if (!methodID_Size_GetWidth || !methodID_Size_GetHeight) {
                break;
            }

            size.width = env->CallIntMethod(localObjectRect, methodID_Size_GetWidth);
            size.height = env->CallIntMethod(localObjectRect, methodID_Size_GetHeight);
        } while (0);

        return size;
    }

    int getDPI() {
        int DPI = -1;

        do {
            JNIEnv *env = LuaJavaHelper::getInstance()->getEnv();
            if (!env) {
                break;
            }

            DPI = LuaJavaHelper::callStaticIntMethod(env, CLASS_NAME_SCREENUTILS,
                                                     METHOD_NAME_SCREENUTILS_GETDPI,
                                                     METHOD_SIG_SCREENUTILS_GETDPI);
        } while (0);

        return DPI;
    }
};